<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>场景管理 - 智能设备控制中心</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .scene-card {
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
            height: 100%;
        }
        .scene-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .scene-active {
            border: 2px solid #0d6efd;
        }
        .card-header {
            font-weight: bold;
        }
        .action-buttons {
            opacity: 0;
            transition: opacity 0.3s;
        }
        .scene-card:hover .action-buttons {
            opacity: 1;
        }
        .modal-backdrop {
            background-color: rgba(0,0,0,0.5);
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm mb-4">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fa fa-home mr-2"></i>智能设备控制中心
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/devices">设备</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/scenes">场景</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/schedules">定时任务</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/analytics">数据分析</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row">
            <div class="col">
                <h2 class="mb-4"><i class="fa fa-magic text-primary"></i> 场景管理</h2>
                <p class="mb-4">场景是一组预定义的设备状态集合，可以一键激活。点击场景卡片激活场景，点击编辑按钮可以自定义场景。</p>
                <button class="btn btn-primary mb-4" data-bs-toggle="modal" data-bs-target="#createSceneModal"><i class="fa fa-plus"></i> 创建新场景</button>
            </div>
        </div>

        <!-- 场景列表 -->
        <div class="row">
            {% for scene in scene_config %}
            <div class="col-md-4 mb-4">
                <div class="card scene-card {{ 'scene-active' if current_scene == scene.name else '' }}">
                    <div class="card-header d-flex justify-content-between">
                        <div>
                            <i class="fa fa-{{ scene.icon }}"></i> {{ scene.name }}
                        </div>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-primary mr-1" onclick="event.stopPropagation(); editScene('{{ scene.name }}')"><i class="fa fa-pencil"></i></button>
                            <button class="btn btn-sm btn-danger" onclick="event.stopPropagation(); deleteScene('{{ scene.name }}')"><i class="fa fa-trash"></i></button>
                        </div>
                    </div>
                    <div class="card-body" onclick="activateScene('{{ scene.name }}')">
                        <p class="card-text text-muted">{{ scene.description }}</p>
                        <div class="mt-2">
                            <p><strong>激活时间：</strong>{{ scene.last_activated or '从未' }}</p>
                        </div>
                        <div class="mt-3">
                            <button class="btn btn-success w-100"><i class="fa fa-play"></i> 激活场景</button>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>

        <!-- AI智能场景建议 -->
        {% if smart_suggestions %}
        <div class="row mt-8">
            <div class="col">
                <h3 class="mb-3"><i class="fa fa-lightbulb-o text-warning"></i> AI智能场景建议</h3>
                <div class="card">
                    <div class="card-body">
                        <p class="card-text mb-4">{{ smart_suggestions.description }}</p>
                        <div class="list-group">
                            {% for suggestion in smart_suggestions.suggestions %}
                            <a href="#" class="list-group-item list-group-item-action" onclick="activateScene('{{ suggestion.scene }}')">
                                <i class="fa fa-arrow-right mr-2"></i>{{ suggestion.description }}
                            </a>
                            {% endfor %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}
    </div>

    <!-- 创建场景模态框 -->
    <div class="modal fade" id="createSceneModal" tabindex="-1" aria-labelledby="createSceneModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createSceneModalLabel">创建新场景</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="createSceneForm">
                        <div class="mb-3">
                            <label for="sceneName" class="form-label">场景名称</label>
                            <input type="text" class="form-control" id="sceneName" required>
                        </div>
                        <div class="mb-3">
                            <label for="sceneDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="sceneDescription" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="sceneIcon" class="form-label">图标</label>
                            <select class="form-control" id="sceneIcon">
                                <option value="home">home</option>
                                <option value="moon-o">moon-o</option>
                                <option value="sun-o">sun-o</option>
                                <option value="film">film</option>
                                <option value="shopping-cart">shopping-cart</option>
                                <option value="coffee">coffee</option>
                                <option value="bed">bed</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">设备状态</label>
                            {% for device in device_config %}
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="device-{{ device.id }}" data-device-id="{{ device.id }}">
                                <label class="form-check-label" for="device-{{ device.id }}">
                                    {{ device.name }} ({{ device.room }})
                                </label>
                            </div>
                            {% endfor %}
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveNewScene()">保存场景</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑场景模态框 -->
    <div class="modal fade" id="editSceneModal" tabindex="-1" aria-labelledby="editSceneModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editSceneModalLabel">编辑场景</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editSceneForm">
                        <input type="hidden" id="editSceneId">
                        <div class="mb-3">
                            <label for="editSceneName" class="form-label">场景名称</label>
                            <input type="text" class="form-control" id="editSceneName" required>
                        </div>
                        <div class="mb-3">
                            <label for="editSceneDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="editSceneDescription" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="editSceneIcon" class="form-label">图标</label>
                            <select class="form-control" id="editSceneIcon">
                                <option value="home">home</option>
                                <option value="moon-o">moon-o</option>
                                <option value="sun-o">sun-o</option>
                                <option value="film">film</option>
                                <option value="shopping-cart">shopping-cart</option>
                                <option value="coffee">coffee</option>
                                <option value="bed">bed</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">设备状态</label>
                            <div id="editSceneDevices"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateScene()">更新场景</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 场景配置数据
        const sceneConfig = {{ scene_config|tojson }};
        const deviceConfig = {{ device_config|tojson }};
        
        // 激活场景
        function activateScene(sceneName) {
            fetch('/api/activate_scene', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ scene_name: sceneName })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 刷新页面
                    location.reload();
                } else {
                    alert('激活失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('激活失败');
            });
        }
        
        // 编辑场景
        function editScene(sceneName) {
            // 查找场景配置
            const scene = sceneConfig.find(s => s.name === sceneName);
            if (!scene) {
                alert('场景不存在');
                return;
            }
            
            // 填充表单
            document.getElementById('editSceneId').value = sceneName;
            document.getElementById('editSceneName').value = scene.name;
            document.getElementById('editSceneDescription').value = scene.description || '';
            document.getElementById('editSceneIcon').value = scene.icon || 'home';
            
            // 填充设备状态
            const devicesContainer = document.getElementById('editSceneDevices');
            devicesContainer.innerHTML = '';
            
            deviceConfig.forEach(device => {
                const isActive = scene.devices && scene.devices[device.id] === true;
                const deviceHtml = `
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="edit-device-${device.id}" data-device-id="${device.id}" ${isActive ? 'checked' : ''}>
                        <label class="form-check-label" for="edit-device-${device.id}">
                            ${device.name} (${device.room})
                        </label>
                    </div>
                `;
                devicesContainer.innerHTML += deviceHtml;
            });
            
            // 显示模态框
            const editModal = new bootstrap.Modal(document.getElementById('editSceneModal'));
            editModal.show();
        }
        
        // 更新场景
        function updateScene() {
            const sceneName = document.getElementById('editSceneId').value;
            const newName = document.getElementById('editSceneName').value;
            const description = document.getElementById('editSceneDescription').value;
            const icon = document.getElementById('editSceneIcon').value;
            
            // 获取设备状态
            const devices = {};
            document.querySelectorAll('#editSceneForm input[type="checkbox"]').forEach(checkbox => {
                const deviceId = parseInt(checkbox.getAttribute('data-device-id'));
                devices[deviceId] = checkbox.checked;
            });
            
            fetch('/api/update_scene', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    scene_name: sceneName,
                    new_name: newName,
                    description: description,
                    icon: icon,
                    devices: devices
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 关闭模态框并刷新页面
                    const editModal = bootstrap.Modal.getInstance(document.getElementById('editSceneModal'));
                    editModal.hide();
                    location.reload();
                } else {
                    alert('更新失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新失败');
            });
        }
        
        // 删除场景
        function deleteScene(sceneName) {
            if (confirm(`确定要删除场景"${sceneName}"吗？`)) {
                fetch('/api/delete_scene', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ scene_name: sceneName })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 刷新页面
                        location.reload();
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败');
                });
            }
        }
        
        // 保存新场景
        function saveNewScene() {
            const name = document.getElementById('sceneName').value;
            const description = document.getElementById('sceneDescription').value;
            const icon = document.getElementById('sceneIcon').value;
            
            // 获取设备状态
            const devices = {};
            document.querySelectorAll('#createSceneForm input[type="checkbox"]').forEach(checkbox => {
                const deviceId = parseInt(checkbox.getAttribute('data-device-id'));
                devices[deviceId] = checkbox.checked;
            });
            
            fetch('/api/create_scene', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: name,
                    description: description,
                    icon: icon,
                    devices: devices
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 关闭模态框并刷新页面
                    const createModal = bootstrap.Modal.getInstance(document.getElementById('createSceneModal'));
                    createModal.hide();
                    location.reload();
                } else {
                    alert('创建失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('创建失败');
            });
        }
    </script>
</body>
</html>